package com.cmwa.scbp.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @author zhougz
 * 压缩下载的工具类
 *
 */
public class HttpDownFileZipUtil {
	
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	// 文件打包下载
	public static HttpServletResponse downLoadFiles(String fileName,Map<String,Map<String,File>> fileMap,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			/**
			 * 这个集合就是你想要打包的所有文件， 这里假设已经准备好了所要打包的文件
			 */
			// List<File> files = new ArrayList<File>();
			/**
			 * 创建一个临时压缩文件， 我们会把文件流全部注入到这个文件中 这里的文件你可以自定义是.rar还是.zip
			 */
			File file = File.createTempFile(UUID.randomUUID().toString(), "zip");
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "Attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1"));
			// response.getWriter()
			// 创建文件输出流
			FileOutputStream fous = new FileOutputStream(file);
			/**
			 * 打包的方法我们会用到ZipOutputStream这样一个输出流, 所以这里我们把输出流转换一下
			 */
			ZipOutputStream zipOut = new ZipOutputStream(fous);
			zipOut.setEncoding("UTF-8");
			for(String key : fileMap.keySet()){
				zipFile(fileMap.get(key), zipOut, key);
			}
			
			zipOut.close();
			fous.close();
			/**
			 * 这个方法接受的就是一个所要打包文件的集合， 还有一个ZipOutputStream
			 */
			
			return downloadZip(file, response, fileName);
		} catch (Exception e) {
			logger.error("HttpDownFileZipUtil====>HttpServletResponse"+e.getMessage());
			e.printStackTrace();
		}
		/**
		 * 直到文件的打包已经成功了， 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中，
		 * 稍后会呈现出来，接下来的就是往客户端写数据了
		 */
		return response;
	}

	/**
	 * 把接受的全部文件打成压缩包
	 * 
	 * @param List
	 *            <File>;
	 * @param org.apache.tools.zip.ZipOutputStream
	 */
	public static void zipFile(Map<String,File> files, ZipOutputStream outputStream,String fileCatalog) {
		Set<String> keySet = files.keySet();
		Iterator<String> it  = keySet.iterator();
		String key = null;
		File file = null;
		while(it.hasNext()){
			key = it.next().toString();
			file = files.get(key);
			zipFile(key,file, outputStream, fileCatalog);
		}
		
	}

	public static HttpServletResponse downloadZip(File file,
			HttpServletResponse response, String fileName) {
		try {
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(
					file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();

			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			response.setContentType("application/octet-stream");
			// 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
			response.setHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode(fileName, "UTF-8"));
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			logger.error("HttpDownFileZipUtil====>downloadZip"+ex.getMessage());
			ex.printStackTrace();
		} finally {
			try {
				File f = new File(file.getPath());
				f.delete();
			} catch (Exception e) {
				logger.error("HttpDownFileZipUtil====>downloadZip"+e.getMessage());
				e.printStackTrace();
			}
		}
		return response;
	}

	/**
	 * 根据输入的文件与输出流对文件进行打包
	 * 
	 * @param File
	 * @param org
	 *            .apache.tools.zip.ZipOutputStream
	 */
	public static void zipFile(String fileName,File inputFile, ZipOutputStream ouputStream, String fileCatalog) {
		try {
			if (inputFile != null && inputFile.exists()) {
				/**
				 * 如果是目录的话这里是不采取操作的， 至于目录的打包正在研究中
				 */
				if (inputFile.isFile()) {
					FileInputStream IN = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(IN, 512);
					// org.apache.tools.zip.ZipEntry
					ZipEntry entry = null;
					if(StringUtils.isNotEmpty(fileCatalog)){
						entry = new ZipEntry(fileCatalog + "/" + fileName);
					}else{
						entry = new ZipEntry(fileName);
					}
					ouputStream.putNextEntry(entry);
					// 向压缩文件中输出数据
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					// 关闭创建的流对象
					bins.close();
					IN.close();
				} else {
						compressDirectory(inputFile,ouputStream);
				}
			}
		} catch (Exception e) {
			logger.error("HttpDownFileZipUtil====>zipFile"+e.getMessage());
			e.printStackTrace();
		}
	}

	private static void compress(String fileName,File file, ZipOutputStream out) {
		/* 判断是目录还是文件 */
		if (file.isDirectory()) {
			logger.debug("压缩："  + file.getName());
			zipFile(fileName,file, out,"");
		} else {
			logger.debug("压缩："  + file.getName());
			zipFile(fileName,file, out,"");
		}
	}

	/** 压缩一个目录 */
	private static void compressDirectory(File dir, ZipOutputStream out) {
		if (!dir.exists())
			return;
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			/* 递归 */
			compress(files[i].getName(),files[i], out);
		}
	}
    
}
